<template>
  <div class="editor-header">
    <div class="left">
      <el-button type="primary" @click="back()">
        {{ $t('back') }}
      </el-button>
      <el-button type="primary" @click="createSlide()">
        <img
          class="icon"
          src="../../../assets//image/icon_/icon-add.png"
          alt=""
        />
        {{ $t('newSlide') }}
      </el-button>
      <Popover trigger="click" placement="bottom-start" center>
        <template #content>
          <LayoutPool
            @select="
              (slide) => {
                createSlideByTemplate(slide)
              }
            "
          />
        </template>
        <div class="menu-item">
          <img
            class="icon_"
            src="../../../assets/image/icon_/icon-Template.png"
            alt=""
          />
        </div>
      </Popover>
    </div>

    <div class="center">
      <div class="title">
        <Input
          class="title-input"
          ref="titleInputRef"
          v-model:value="titleValue"
          @blur="handleUpdateTitle()"
          v-if="editingTitle"
        ></Input>
        <div class="title-text" @click="startEditTitle()" :title="title" v-else>
          <span>{{ title }}</span>
          <img
            class="icon"
            src="../../../assets/image/icon_/icon-edit.png"
            style="margin-left: 4px"
          />
        </div>
      </div>
    </div>
    <div class="right">
      <div style="display: flex; gap: 6px">
        <!-- 设为默认布局 -->
        <Button
          size="small"
          style="background-color: #169bd5; color: #ffffff"
          @click="handleSetAsDefaultLayout"
          v-if="
            (isProposalLayoutCreate || isProposalLayoutEdit) && isDefault !== 1
          "
        >
          {{ $t('setAsDefaultLayout') }}
        </Button>
        <!-- 更新/保存布局 -->
        <Button
          size="small"
          style="background-color: #169bd5; color: #ffffff"
          @click="handleSaveLayout"
          v-if="isProposalLayoutCreate || isProposalLayoutEdit"
        >
          {{ isProposalLayoutCreate ? $t('saveLayout') : $t('updateLayout') }}
        </Button>
        <!-- 设为默认模板 -->
        <Button
          size="small"
          style="background-color: #169bd5; color: #ffffff"
          @click="handleSetAsDefaultTemplate"
          v-if="(isModuleCreate || isModuleEdit) && isDefault !== 1"
        >
          {{ $t('setAsDefaultTemplate') }}
        </Button>
        <!-- 保存模板 -->
        <Button
          size="small"
          style="background-color: #169bd5; color: #ffffff"
          @click="handleAddTemplateData"
          v-if="isModuleCreate"
        >
          {{ $t('saveTemplate') }}
        </Button>
        <!-- 更新模板 -->
        <Button
          size="small"
          style="background-color: #169bd5; color: #ffffff"
          @click="handleUpdateTemplateData"
          v-if="isModuleEdit"
        >
          {{ $t('updateTemplate') }}
        </Button>
        <Button
          size="small"
          style="background-color: #169bd5; color: #ffffff"
          @click="handleUpdateProposalData"
          v-if="isProposalEdit"
        >
          {{ $t('updateProposal') }}
        </Button>
        <Button
          size="small"
          style="background-color: #169bd5; color: #ffffff"
          @click="closeProposalDialog = true"
          v-if="isProposalEdit"
        >
          {{ $t('closeProposal') }}
        </Button>
        <Button
          size="small"
          style="background-color: #169bd5; color: #ffffff"
          @click="handleSaveProposalData"
          v-if="isProposalCreate"
        >
          {{ $t('saveProposal') }}
        </Button>
      </div>
      <div class="menu-item" v-tooltip="$t('tooltipImport')">
        <img
          class="icon"
          src="../../../assets/image/icon_/icon-input.png"
          alt=""
        />
        <FileInput
          class="file_sty"
          accept=".pptist"
          @change="
            (files) => {
              importSpecificFile(files)
              mainMenuVisible = false
            }
          "
        >
          <PopoverMenuItem>{{ $t('importPptistFile') }}</PopoverMenuItem>
        </FileInput>
      </div>
      <div class="group-menu-item">
        <div
          class="menu-item"
          v-tooltip="$t('tooltipScreening')"
          @click="enterScreening()"
        >
          <img
            class="icon"
            src="../../../assets/image/icon_/icon-playBack.png"
            alt=""
          />
          {{ $t('screening') }}
        </div>
        <Popover trigger="click" center>
          <template #content>
            <PopoverMenuItem @click="enterScreeningFromStart()">
              {{ $t('startScreening') }}
            </PopoverMenuItem>
            <PopoverMenuItem @click="enterScreening()">
              {{ $t('startScreeningFromCurrent') }}
            </PopoverMenuItem>
          </template>
          <div class="arrow-btn"><IconDown class="arrow" /></div>
        </Popover>
      </div>
      <div
        class="menu-item"
        v-tooltip="$t('tooltipExport')"
        @click="setDialogForExport('pptx')"
      >
        <img
          class="icon"
          src="../../../assets/image/icon_/icon-download.png"
          alt=""
        />
        {{ $t('download') }}
      </div>
    </div>

    <Drawer
      :width="320"
      v-model:visible="hotkeyDrawerVisible"
      placement="right"
    >
      <HotkeyDoc />
      <template v-slot:title>快捷操作</template>
    </Drawer>

    <FullscreenSpin :loading="exporting" tip="正在导入..." />
    <FullscreenSpin :loading="loading" :tip="tip" />
    <ExportImage ref="exportRef" style="position: absolute; left: -100%" />

    <el-dialog v-model="closeProposalDialog" title="闭合提案" width="500">
      <h3>{{ $t('closeProposalDialog') }}</h3>
      <p style="color: #d7d7d7">{{ $t('closeProposalDialogInfo') }}</p>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeProposalDialog = false">{{
            $t('cancel')
          }}</el-button>
          <el-button
            type="primary"
            @click="handleUpdateProposalDataAndCloseDialog"
          >
            {{ $t('confirm') }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { nextTick, ref, computed } from 'vue'

import { storeToRefs } from 'pinia'
import { ElDialog, ElButton, ElMessageBox } from 'element-plus'
import { useMainStore, useSlidesStore, useProposalStore } from '@/store'
import useScreening from '@/hooks/useScreening'
import useImport from '@/hooks/useImport'
import useSlideHandler from '@/hooks/useSlideHandler'
import type { DialogForExportTypes } from '@/types/export'

import HotkeyDoc from './HotkeyDoc.vue'
import FileInput from '@/components/FileInput.vue'
import FullscreenSpin from '@/components/FullscreenSpin.vue'
import Drawer from '@/components/Drawer.vue'
import Input from '@/components/Input.vue'
import Popover from '@/components/Popover.vue'
import PopoverMenuItem from '@/components/PopoverMenuItem.vue'
import Button from '@/components/Button.vue'
import ExportImage from '@/views/Editor/ExportDialog/ExportImage.vue'
import LayoutPool from '../Thumbnails/LayoutPool.vue'
import message from '@/utils/message'

import { useI18n } from 'vue-i18n'
import useProposalOrTemplate from '@/hooks/useProposalOrTemplate'

const mainStore = useMainStore()
const slidesStore = useSlidesStore()
const { title } = storeToRefs(slidesStore)
const { enterScreening, enterScreeningFromStart } = useScreening()
const { importSpecificFile, importPPTXFile, exporting } = useImport()
const { resetSlides, createSlide, createSlideByTemplate } = useSlideHandler()
const { t } = useI18n()

const useFetch = useProposalOrTemplate()
const proposalStore = useProposalStore()
const {
  isProposalEdit,
  isModuleEdit,
  isProposalCreate,
  isModuleCreate,
  isProposalLayoutCreate,
  isProposalLayoutEdit,
  isProposalLayoutView,
  layoutType,
  isDefault,
  lastDefaultLayoutName,
} = storeToRefs(proposalStore)
const {
  saveProposalData,
  updateProposalData,
  addTemplateData,
  updateTemplateData,
  closeProposalData,
  setCoverImage,
  addLayoutFile,
  updateLayoutFile,
} = proposalStore

const mainMenuVisible = ref(false)
const hotkeyDrawerVisible = ref(false)
const editingTitle = ref(false)
const titleInputRef = ref<InstanceType<typeof Input>>()
const titleValue = ref('')
const closeProposalDialog = ref(false)
const loading = ref(false)
const tip = ref('处理中...')

const exportRef = ref()
// const isProposalLayout = computed(() => {
//   return isProposalLayoutCreate.value || isProposalLayoutEdit.value || isProposalLayoutView.value
// })

const back = () => {
  window.parent.postMessage({ action: 'goBack' }, '*')
}

const getCoverImage = async () => {
  // 当前页的文件流存入仓库
  const imageFile = await exportRef.value?.expImage({ file: true }, 'home')
  await setCoverImage(imageFile)
}

const handleUpdateProposalDataAndCloseDialog = async () => {
  try {
    loading.value = true
    closeProposalDialog.value = false
    await updateProposalData()
    await closeProposalData()
    loading.value = false
    goBack()
  }
  catch (e) {
    // eslint-disable-next-line no-console
    console.error(e)
    loading.value = false
  }
}

const handleSaveProposalData = async () => {
  try {
    loading.value = true
    await getCoverImage()
    await saveProposalData()
    loading.value = false
    goBack()
  }
  catch (e) {
    // eslint-disable-next-line no-console
    console.error(e)
    loading.value = false
  }
}

const handleUpdateProposalData = async () => {
  try {
    loading.value = true
    await getCoverImage()
    await updateProposalData()
    loading.value = false
    goBack()
  }
  catch (e) {
    // eslint-disable-next-line no-console
    console.error(e)
    loading.value = false
  }
}

const handleAddTemplateData = async () => {
  try {
    loading.value = true

    await getCoverImage()
    await addTemplateData()
    goBack()
  }
  catch (e) {
    // eslint-disable-next-line no-console
    console.error(e)
    loading.value = false
  }
}

const handleUpdateTemplateData = async () => {
  try {
    loading.value = true
    await getCoverImage()

    await updateTemplateData()
    loading.value = false
    goBack()
  }
  catch (e) {
    // eslint-disable-next-line no-console
    console.error(e)
    loading.value = false
  }
}

const handleSaveLayout = async () => {
  try {
    await getCoverImage()

    if (isProposalLayoutCreate.value) {
      await addLayoutFile()
    }
    else if (isProposalLayoutEdit.value) {
      await updateLayoutFile()
    }
    goBack()
  }
  catch (e) {
    // eslint-disable-next-line no-console
    console.error(e)
    loading.value = false
  }
}

const handleSetAsDefaultLayout = async () => {
  try {
    await ElMessageBox.confirm(t('setDefaultLayoutConfirm'), '', {
      confirmButtonText: t('confirm'),
      cancelButtonText: t('cancel'),
      type: 'warning',
    }).then(async () => {
      await useFetch.setDefaultLayout({
        layoutId: proposalStore.layoutId!,
        itemType: proposalStore.itemType!,
        layoutType: proposalStore.layoutType!,
        proposalLayoutType: proposalStore.proposalLayoutType!,
      })
      message.success(t('success'))
    })
  }
  catch (e) {
    // eslint-disable-next-line no-console
    console.error(e)
    loading.value = false
  }
}

const handleSetAsDefaultTemplate = async () => {
  try {
    await ElMessageBox.confirm(t('setDefaultTemplateConfirm'), '', {
      confirmButtonText: t('confirm'),
      cancelButtonText: t('cancel'),
      type: 'warning',
    }).then(async () => {
      await useFetch.setDefaultTemplate({
        moudleId: proposalStore.moudleId!,
        itemType: proposalStore.itemType!,
        moudleType: proposalStore.moudleType!,
      })
      message.success(t('success'))
    })
  }
  catch (e) {
    // eslint-disable-next-line no-console
    console.error(e)
    loading.value = false
  }
}

const goBack = () => {
  if (isProposalCreate.value) {
    window.history.back()
  }
  window.history.back()
}
const startEditTitle = () => {
  titleValue.value = title.value
  editingTitle.value = true
  nextTick(() => titleInputRef.value?.focus())
}

const handleUpdateTitle = () => {
  slidesStore.setTitle(titleValue.value)
  editingTitle.value = false
}

const goLink = (url: string) => {
  window.open(url)
  mainMenuVisible.value = false
}

const setDialogForExport = (type: DialogForExportTypes) => {
  mainStore.setDialogForExport(type)
  mainMenuVisible.value = false
}
</script>

<style lang="scss" scoped>
.left .el-button--primary {
  color: #fff;
  background-color: #3170ff;
  border-color: #3170ff;
  border-radius: 8px;
  margin-left: 20px;
  font-size: 12px;
}
.editor-header {
  background-color: #fff;
  user-select: none;
  border-bottom: 1px solid $borderColor;
  border-top: 1px solid $borderColor;
  display: flex;
  justify-content: space-between;
  padding: 0 5px;

  .icon {
    width: 12px;
    height: 12px;
    margin-right: 2px;
  }
  .file_sty {
    .popover-menu-item {
      min-width: auto;
      padding: 0;
    }
  }
}
.left,
.right {
  display: flex;
  justify-content: center;
  align-items: center;
}
.menu-item {
  height: 30px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 12px;
  padding: 0 10px;
  color: #333;
  border-radius: $borderRadius;
  cursor: pointer;

  .icon_ {
    width: 20px;
    height: 20px;
    margin-left: 10px;
  }

  &:hover {
    background-color: #f1f1f1;
  }
}
.group-menu-item {
  height: 30px;
  display: flex;
  margin: 0 8px;
  padding: 0 2px;
  border-radius: $borderRadius;

  &:hover {
    background-color: #f1f1f1;
  }

  .menu-item {
    padding: 0 3px;
  }
  .arrow-btn {
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
  }
}
.title {
  height: 56px;
  margin-left: 2px;
  font-size: 16px;
  font-weight: bold;
  color: #333;
  .title-input {
    width: 200px;
    height: 100%;
    padding-left: 0;
    padding-right: 0;
  }
  .title-text {
    min-width: 20px;
    max-width: 400px;
    line-height: 56px;
    padding: 0 6px;
    border-radius: $borderRadius;
    cursor: pointer;

    @include ellipsis-oneline();

    &:hover {
      background-color: #f1f1f1;
    }
  }
}
.github-link {
  display: inline-block;
  height: 30px;
}
</style>
